﻿using System;
using System.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using Microsoft.Phone.Reactive;
using CCWP7.Model;

namespace CCWP7.Bare
{
    public class MainViewModel : INotifyPropertyChanged
    {
        readonly IServerDataManager severDataManager;

        public MainViewModel()
        {
            this.Items = new ObservableCollection<ItemViewModel>();
            this.severDataManager = App.ServerDataManager;
        }

        Frame Frame { get { return (Frame)App.Current.RootVisual; } }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<ItemViewModel> Items { get; set; }
        
        public bool IsDataLoaded { get; set; }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            var requests = from server in severDataManager.Servers
                           select HttpWebRequest.CreateHttp(server.Uri);

            var observables = from rq in requests
                              let ob = Observable.FromAsyncPattern<WebResponse>(rq.BeginGetResponse, rq.EndGetResponse)
                              select ob().ObserveOnDispatcher();

            this.IsDataLoaded = true;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void AddServer()
        {
            Frame.Navigate(new Uri("/AddServerPage.xaml", UriKind.Relative));
        }

        public void RefreshAll()
        {
            // TODO: Refresh All
        }

        public void About()
        {
            Frame.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }
    }
}